<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--规则数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="规则ID" prop="ruleId">
            <el-input
              v-model="queryParams.ruleId"
              placeholder="请输入规则ID"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="模式" prop="schemaName">
            <el-input
              v-model="queryParams.schemaName"
              placeholder="请输入模式"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="是否启用规则"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.rule_monitor_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="表名" prop="tableName">
            <el-input
              v-model="queryParams.tableName"
              placeholder="请输入创建人"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="createBy">
            <el-input
              v-model="queryParams.createBy"
              placeholder="请输入创建人"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['rule:monitor:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['rule:monitor:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['rule:monitor:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="规则ID" align="center" key="ruleId" prop="ruleId" />
          <el-table-column label="模式" align="center" key="schemaName" prop="schemaName" :show-overflow-tooltip="true" />
          <el-table-column label="表名" align="center" key="tableName" prop="tableName" :show-overflow-tooltip="true" />
          <el-table-column label="脚本名" align="center" key="sqlName" prop="sqlName" :show-overflow-tooltip="true" />
          <el-table-column label="校验类型" align="center" key="checkType" prop="checkType" width="120" />
          <el-table-column label="校验级别" align="center" key="checkGrade" prop="checkGrade"  width="120" />
          <el-table-column label="计算规则" align="center" key="checkGrade" prop="checkGrade" v-if="columns[0].visible"  width="120" />
          <el-table-column label="字段名" align="center" key="fieldName" prop="fieldName"  width="120" />
          <el-table-column label="比较值" align="center" key="compareValue" prop="compareValue" v-if="columns[1].visible"  width="120" />
          <el-table-column label="过滤条件" align="center" key="filterCondition" prop="filterCondition" width="120" />
          <el-table-column label="校验周期" align="center" key="checkCycle" prop="checkCycle"  width="120" />
          <el-table-column label="是否启用" align="center" key="status" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="sql模版" align="center" key="sqlTemplate" prop="sqlTemplate" v-if="columns[2].visible"  width="120" />
          <el-table-column label="执行sql" align="center" key="executeSql" prop="executeSql" v-if="columns[3].visible"  width="120" />
          <el-table-column label="作业日期" align="center" key="workDate" prop="workDate" v-if="columns[4].visible"  width="120" />
          <el-table-column label="对照组日期" align="center" key="cpDate" prop="cpDate" v-if="columns[5].visible"  width="120" />
          <el-table-column label="创建者" align="center" key="createBy" prop="createBy" v-if="columns[6].visible"  width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
           <el-table-column label="更新者" align="center" key="updateBy" prop="updateBy" v-if="columns[8].visible"  width="120" />
          <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns[9].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['rule:monitor:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改规则配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="模式名" prop="schemaName" required>
              <el-input v-model="form.schemaName" placeholder="请输入模式名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="表名" prop="tableName" required>
              <el-input v-model="form.tableName" placeholder="请输入表名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="脚本名" prop="sqlName" required>
              <el-input v-model="form.sqlName" placeholder="请输入脚本名" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="校验类型" prop="checkType" required>
              <el-select
              v-model="form.checkType"
              placeholder="请选择校验类型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.check_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校验级别" prop="checkGrade">
             <el-select
              v-model="form.checkGrade"
              placeholder="请选择校验级别"
              clearable
            >
              <el-option
                v-for="dict in dict.type.check_grade"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计算规则" prop="calRule">
              <el-input v-model="form.calRule" placeholder="请输入计算规则" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="字段名" prop="fieldName">
              <el-input v-model="form.fieldName" placeholder="请输入字段名"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="比较值" prop="compareValue">
              <el-input v-model="form.compareValue" placeholder="请输入比较值" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校验周期" prop="checkCycle">
              <el-select
              v-model="form.checkCycle"
              placeholder="请选择校验级别"
              clearable
            >
              <el-option
                v-for="dict in dict.type.check_cycle"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="作业日期" prop="workDate">
              <el-date-picker
                v-model="form.workDate"
                type="date"
                placeholder="请输入作业日期"
                value-format="yyyy-MM-dd"
                style="width: 196px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对照组日期" prop="cpDate">
              <el-date-picker
                v-model="form.cpDate"
                type="date"
                placeholder="请输入对照组日期"
                value-format="yyyy-MM-dd"
                style="width: 196px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" required>
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.rule_monitor_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
         <el-col :span="24">
            <el-form-item label="过滤条件" prop="filterCondition">
              <el-input v-model="form.filterCondition" placeholder="请输入过滤条件" maxlength="50" >
                <template #prepend>where</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="sql模版">
              <el-input v-model="form.sqlTemplate" type="textarea" placeholder="请输入sql模版"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="执行sql">
              <el-input v-model="form.executeSql" type="textarea" placeholder="请输入执行sql"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 规则导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的规则数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRule, getRule, delRule, changeUserStatus, updateRule, addRule } from "@/api/rule/monitor/index.js";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['rule_monitor_status', 'check_type', 'check_grade', 'check_cycle'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则表格数据
      ruleList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 规则导入参数
      upload: {
        // 是否显示弹出层（规则导入）
        open: false,
        // 弹出层标题（规则导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的规则数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/rule/monitor/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        ruleId: undefined,
        schemaName: undefined,
        createBy: undefined,
        createTime: undefined,
        tableName: undefined,
      },
      // 列信息
      columns: [
        // { key: 0, label: `规则ID`, visible: false },
        // { key: 1, label: `模式`, visible: true },
        // { key: 2, label: `表名`, visible: true },
        // { key: 3, label: `脚本名`, visible: true },
        // { key: 4, label: `校验类型`, visible: true },
        // { key: 5, label: `校验级别`, visible: true },
        { key: 6, label: `计算规则`, visible: false },
        // { key: 7, label: `字段名`, visible: true },
        { key: 8, label: `比较值`, visible: false },
        // { key: 9, label: `过滤条件`, visible: true },
        // { key: 10, label: `校验周期`, visible: true },
        // { key: 11, label: `是否启用`, visible: true },
        { key: 12, label: `sql模版`, visible: false },
        { key: 13, label: `执行sql`, visible: false },
        { key: 14, label: `作业日期`, visible: false },
        { key: 15, label: `对照组日期`, visible: false },
        { key: 16, label: `创建者`, visible: false },
        { key: 17, label: `创建时间`, visible: false },
        { key: 18, label: `更新者`, visible: false },
        { key: 19, label: `更新时间`, visible: false },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '规则名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "规则昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "规则密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '规则密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询规则列表 */
    getList() {
      this.loading = true;
      listRule(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.ruleList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    // 规则状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要' + text + '"' + row.ruleId + '" 吗？').then(function() {
        return changeUserStatus(row.ruleId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: undefined,
        schemaName: undefined,
        status: undefined,
        tableName: undefined,
        createBy: undefined,
        createTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规则监控";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids;
      getRule(ruleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改规则监控";
      });
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != undefined) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除规则编号为"' + ruleIds + '"的数据项？').then(function() {
        return delRule(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rule/monitor/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "规则导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('rule/monitor/importTemplate', {
      }, `rule_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
